/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.hydms.healthcheck.web;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.hydms.healthcheck.entity.DmsHealthCheck;
import com.thinkgem.jeesite.modules.hydms.healthcheck.service.DmsHealthCheckService;
import com.thinkgem.jeesite.modules.hydms.students.entity.DmsStudents;

/**
 * 卫生检查Controller
 * @author 刘健
 * @version 2017-04-05
 */
@Controller
@RequestMapping(value = "${adminPath}/healthcheck/dmsHealthCheck")
public class DmsHealthCheckController extends BaseController {

	@Autowired
	private DmsHealthCheckService dmsHealthCheckService;
	
	@ModelAttribute
	public DmsHealthCheck get(@RequestParam(required=false) String id) {
		DmsHealthCheck entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = dmsHealthCheckService.get(id);
		}
		if (entity == null){
			entity = new DmsHealthCheck();
		}
		return entity;
	}
	
	
	/**
	 * 查找宿舍信息
	 * @param checkResult
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("healthcheck:dmsHealthCheck:view")
	@RequestMapping(value = "checkResult")
	public void checkResult(DmsHealthCheck dmsHealthCheck, HttpServletRequest request,String idDorNum,Date idCheD,HttpServletResponse response, Model model) {
		dmsHealthCheck.setCheckDate(idCheD);
		dmsHealthCheck.setDormitoryNumber(idDorNum);
		List<DmsHealthCheck> list = dmsHealthCheckService.findList(dmsHealthCheck);
	
		if(list.size()>0){
			try {
				response.getWriter().print("null");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	

	/**
	 * 导出用户数据
	 * @param dmsHealthCheck
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("healthcheck:dmsHealthCheck:view")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(DmsHealthCheck dmsHealthCheck, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "宿舍卫生信息"+DateUtils.getDate("yyyyMMdd")+".xlsx";
            Page<DmsHealthCheck> page = dmsHealthCheckService.findPage(new Page<DmsHealthCheck>(request, response, -1), dmsHealthCheck);
    		new ExportExcel("宿舍卫生信息", DmsHealthCheck.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出卫生信息失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/healthcheck/dmsHealthCheck/list?repage";
    }
	/**
	 * 导入用户数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("healthcheck:dmsHealthCheck:edit")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:"+Global.getAdminPath()+"/healthcheck/dmsHealthCheck/list?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<DmsHealthCheck> list = ei.getDataList(DmsHealthCheck.class);
		
			for (DmsHealthCheck dmsHealthCheck : list){
				try{
					if ((dmsHealthCheckService.findList(dmsHealthCheck).size()<1)){
						BeanValidators.validateWithException(validator, dmsHealthCheck);
						dmsHealthCheckService.save(dmsHealthCheck);
						successNum++;
					}else{
						failureMsg.append("<br/>检查日期 "+dmsHealthCheck.getCheckDate()+"<br/>宿舍号"+dmsHealthCheck.getDormitoryNumber()+" 已存在; ");
						failureNum++;
					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>检查日期 "+dmsHealthCheck.getCheckDate()+"<br/>宿舍号"+dmsHealthCheck.getDormitoryNumber()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("<br/>检查日期 "+dmsHealthCheck.getCheckDate()+"<br/>宿舍号"+dmsHealthCheck.getDormitoryNumber()+" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条用户，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条用户"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入用户失败！失败信息："+e.getMessage());
		}
		return "redirect:"+adminPath+"/healthcheck/dmsHealthCheck/list?repage";

    }
	
	/**
	 * 下载导入学生数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("healthcheck:dmsHealthCheck:view")
    @RequestMapping(value = "template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "宿舍卫生数据导入模板.xlsx";
    		List<DmsHealthCheck> list = Lists.newArrayList(); 
    		new ExportExcel("宿舍卫生数据", DmsHealthCheck.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/healthcheck/dmsHealthCheck/list?repage";
    }


	/**
	 * 卫生检查列表
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	
	@RequiresPermissions("healthcheck:dmsHealthCheck:view")
	@RequestMapping(value = {"list", ""})
	public String list(DmsHealthCheck dmsHealthCheck, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<DmsHealthCheck> page = dmsHealthCheckService.findPage(new Page<DmsHealthCheck>(request, response), dmsHealthCheck); 
		model.addAttribute("page", page);
		return "hydms/healthcheck/dmsHealthCheckList";
	}

	/**
	 * 卫生检查添加
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("healthcheck:dmsHealthCheck:view")
	@RequestMapping(value = "form")
	public String form(DmsHealthCheck dmsHealthCheck, Model model) {
		model.addAttribute("dmsHealthCheck", dmsHealthCheck);
		return "hydms/healthcheck/dmsHealthCheckForm";
	}
	
/*	@RequiresPermissions("healthcheck:dmsHealthCheck:view")
	@RequestMapping(value = "form2")
	public String form2(DmsHealthCheck dmsHealthCheck, Model model) {
		model.addAttribute("dmsHealthCheck", dmsHealthCheck);
		return "hydms/healthcheck/dmsHealthCheckForm2";
	}*/

	/**
	 * save
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("healthcheck:dmsHealthCheck:edit")
	@RequestMapping(value = "save")
	public String save(DmsHealthCheck dmsHealthCheck, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, dmsHealthCheck)){
			return form(dmsHealthCheck, model);
		}
		dmsHealthCheckService.save(dmsHealthCheck);
		addMessage(redirectAttributes, "保存卫生检查成功");
		return "redirect:"+Global.getAdminPath()+"/healthcheck/dmsHealthCheck/?repage";
	}
	
	/**
	 * delete
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("healthcheck:dmsHealthCheck:edit")
	@RequestMapping(value = "delete")
	public String delete(DmsHealthCheck dmsHealthCheck, RedirectAttributes redirectAttributes) {
		dmsHealthCheckService.delete(dmsHealthCheck);
		addMessage(redirectAttributes, "删除卫生检查成功");
		return "redirect:"+Global.getAdminPath()+"/healthcheck/dmsHealthCheck/?repage";
	}

}